/**
 * 
 */
package com.android.dwt.ui;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.dwt.Position;
import com.android.dwt.R;
import com.android.dwt.R.id;
import com.android.dwt.R.layout;
import com.android.dwt.data.GTDApp;
import com.android.dwt.util.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * The Class MgrPositionAct.
 *
 * @author xiang
 * 
 */
public class MgrPositionAct extends Activity
		implements OnClickListener, OnItemClickListener, DialogInterface.OnClickListener {
	
	public static final int BG_COLOR = 0xff444444;
	public static final int FG_COLOR = 0xffff0000;
	private final String TAG = "MgrPositionAct";
	private final String[] mFromCols = new String[] { "item_place", "item_addr" };
	private final int[] mToLayouts = new int[] { R.id.tv_pos_place, R.id.tv_pos_addr };
	
	private ListView mListView;
	private MyAdapter mAdapter;
	private ArrayList<HashMap<String, Object>> mItems;
	private GTDApp mGa;
	private int mSelectIndex = 0;		// position of current selected item
	private View mSelectedView;
	private Button mAdd;
	private Button mEdit;
	private Button mDelete;
	private HashMap<Integer, Boolean> mStates; 		// save radiobutton state
	private HashMap<Integer, Integer> mColor;
	
	
	private class MyAdapter extends SimpleAdapter
			implements OnCheckedChangeListener {
		
		private LayoutInflater mInflater;
		private ArrayList<HashMap<String, Object>> mData;
		private ViewHolder mHolder;
		
		
		private final class ViewHolder {
			TextView flag;
			RadioButton rb;
			TextView place;
			TextView address;
		}

		
		@SuppressWarnings("unchecked")
		public MyAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			
			super(context, data, resource, from, to);
			
			Log.e(TAG, "MyAdapter will be initialized!");
			
			mData = (ArrayList<HashMap<String, Object>>) data;
			mInflater = LayoutInflater.from(context);
			
			mStates = new HashMap<Integer, Boolean>();
			mColor = new HashMap<Integer, Integer>();
			
			mStates.put(0, true);
			mColor.put(0, FG_COLOR);
			for (int i=1; i<mData.size(); i++) {
				
				mStates.put(i, false);
				mColor.put(i, BG_COLOR);
			}
			
		}
		
		public HashMap<Integer, Integer> getColor() {
			
			return mColor;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
//			return super.getView(position, convertView, parent);
			
			Log.e(TAG, "fill row " + position);
			
			if (convertView == null) {
				
				convertView = mInflater.inflate(R.layout.row_pos, null);
				
//				Log.e(TAG, "position "+position+" is null!");
				
				mHolder = new ViewHolder();
				mHolder.flag = (TextView) convertView.findViewById(R.id.tv_pos_cur);
				mHolder.rb = (RadioButton) convertView.findViewById(R.id.rb_selected);
				mHolder.place = (TextView) convertView.findViewById(R.id.tv_pos_place);
				mHolder.address = (TextView) convertView.findViewById(R.id.tv_pos_addr);
				
				convertView.setTag(mHolder);
				
			} else {
				
//				Log.e(TAG, "position "+position+" is not null!");
				
				mHolder = (ViewHolder) convertView.getTag();
			}
			
			if (mSelectIndex == position) {
				
				Log.e(TAG, "mSelectIndex = position: " + position);
				
				mSelectedView = convertView;
			}
			
//			Log.e(TAG, "view position " + position + " " + mSelectedView.getId());
			
			// populate data
			if (mColor.get(position) == BG_COLOR) {
				
//				mHolder.flag.setBackgroundColor(BG_COLOR);
				mHolder.flag.setBackgroundColor(Color.TRANSPARENT);
				
			} else {
				
				mHolder.flag.setBackgroundColor(FG_COLOR);
			}
			
			mHolder.rb.setChecked(mStates.get(position));
			
			Log.e(TAG, "selected color: " + mColor.get(position)
					+ " " + mStates.get(position));
			
			String place = (String) mData.get(position).get("item_place");
			mHolder.place.setText(place);
			
			String addr = (String) mData.get(position).get("item_addr");
			mHolder.address.setText(addr);
			
			return convertView;
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		Log.e(TAG, "onCreate is called!");
		
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.mgr_pos);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_loc);
		
		initViews();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		Log.e(TAG, "onResume is called!");
		
//		refreshAdapterData();
		mAdapter.notifyDataSetChanged();
		
		Log.e(TAG, "mSelectIndex is: " + mSelectIndex);
	}
	
	private void initViews() {
		
		mGa = (GTDApp) this.getApplication();
		
		mItems = new ArrayList<HashMap<String,Object>>();
		mListView = (ListView) this.findViewById(R.id.lv_pos);
		
		mAdd = (Button) findViewById(R.id.btn_pos_add);
		mEdit = (Button) findViewById(R.id.btn_pos_edit);
		mDelete = (Button) findViewById(R.id.btn_pos_del);
		
		getAdapterData();
		mAdapter = new MyAdapter(
				MgrPositionAct.this,
				mItems,
				R.layout.row_pos,
				mFromCols,
				mToLayouts);
		mListView.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		
		mListView.setOnItemClickListener(this);
		mAdd.setOnClickListener(this);
		mEdit.setOnClickListener(this);
		mDelete.setOnClickListener(this);
		
		ImageButton ibReturn = (ImageButton) findViewById(R.id.ib_loc_return);
		ibReturn.setOnClickListener(this);
		ibReturn.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					
					v.setBackgroundResource(R.drawable.back_pressed);
					
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					
					v.setBackgroundResource(R.drawable.back);
				}

				return false;
			}
			
		});
	}
	
	private void refreshAdapterData() {
		
		getAdapterData();
	}
	
	private void getAdapterData() {
		
		HashMap<String, Object> hm = null;
		String place, address;
		int lat, lng;
		
		mItems.clear();
		ArrayList<Position> mPos = mGa.getPositions();
		
		for (int i=0; i<mPos.size(); i++) {
			
			place = mPos.get(i).getPlace();
			address = mPos.get(i).getAddress();
			lat = mPos.get(i).getLatitude();
			lng = mPos.get(i).getLongtitude();
			
			hm = new HashMap<String, Object>();
			hm.put("item_place", place);
			hm.put("item_addr", address);
			hm.put("item_lat", lat);
			hm.put("item_lng", lng);
			
			mItems.add(hm);
		}
		
	}
	
	public void setColor(HashMap<Integer, Integer> color) {
		
		this.mColor = color;
	}
	
	public HashMap<Integer, Boolean> getStates() {
		
		return mStates;
	}
	
	public void setStates(HashMap<Integer, Boolean> states) {
		
		this.mStates = states;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch (v.getId()) {
		
    		case R.id.btn_pos_add:
    			
    			Intent itt = new Intent(MgrPositionAct.this, MapManagerAct.class);
    			
    			startActivityForResult(itt, 0);
    			
    			break;
    			
    		case R.id.btn_pos_edit:
    			
    			HashMap<String, Object> hm = (HashMap<String, Object>) mListView.getItemAtPosition(mSelectIndex);
    			
    			AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			builder.setTitle("编辑位置");
    			
    			LayoutInflater li = LayoutInflater.from(this);
    		    View view = li.inflate(R.layout.prompt_view, null);
    		    
    		    builder.setView(view);
    		    builder.setPositiveButton("确定", this);
    		    builder.setNegativeButton("取消", this);
    		    
    		    EditText et = (EditText) view.findViewById(R.id.et_prompt);
    		    et.setText((String) hm.get("item_place"));
    		    et.selectAll();
    		    
    		    TextView tv = (TextView) view.findViewById(R.id.tv_prompt);
    		    tv.setText((String) hm.get("item_addr"));
    		    
    		    builder.create().show();  
    			
    			break;
    			
    		case R.id.btn_pos_del:
    			
//    			Position position = mGa.getPositions().get(mSelectIndex);
    			mGa.getPositions().remove(mSelectIndex);
    			
    			refreshAdapterData();
    			mAdapter.notifyDataSetChanged();
    			
    			break;
    			
    		case R.id.ib_loc_return:
    			
    			finish();
    			
    			break;
    			
    		default:
    			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
//		super.onActivityResult(requestCode, resultCode, data);
		
		switch (resultCode) {
		
    		case RESULT_OK:
    			
    			int size = mItems.size();
    			
    			refreshAdapterData();
    			
    			for (int i=size; i<mItems.size(); i++) {
    				
    				mStates.put(i, false);
    				mColor.put(i, BG_COLOR);
    			}
    			
//    			mStates.put(mItems.size()-1, false);
//    			mColor.put(mItems.size()-1, BG_COLOR);
    			
    			mAdapter.notifyDataSetChanged();
    			
    			break;
    			
    		case RESULT_CANCELED:
    			break;
    			
    		default:
    			break;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		@SuppressWarnings("unchecked")
		HashMap<String, Object> hm = (HashMap<String, Object>) mListView.getItemAtPosition(position);
		double lat = ((Integer) hm.get("item_lat")).intValue()/1e6;
		double lng = ((Integer) hm.get("item_lng")).intValue()/1e6;
		
		Log.e(TAG, "current location: ("+lat+","+lng+")");
		Log.e(TAG, "Current position: " + position);
		Log.e(TAG, "mSelectIndex: " + mSelectIndex);
		
		RadioButton rb = (RadioButton) view.findViewById(R.id.rb_selected);
		TextView tv = (TextView) view.findViewById(R.id.tv_pos_cur);
		
		((RadioButton) mSelectedView.findViewById(R.id.rb_selected)).setChecked(false);
//		((TextView) mSelectedView.findViewById(R.id.tv_pos_cur)).setBackgroundColor(BG_COLOR);
		((TextView) mSelectedView.findViewById(R.id.tv_pos_cur)).setBackgroundColor(Color.TRANSPARENT);
//		((TextView) mSelectedView.findViewById(R.id.tv_pos_cur)).setBackgroundColor(Color.WHITE);
		
		rb.setChecked(true);
		tv.setBackgroundColor(FG_COLOR);
		
		// save states
		HashMap<Integer, Boolean> hmRb = getStates();
		hmRb.put(mSelectIndex, false);
		hmRb.put(position, true);
		setStates(hmRb);
		
		HashMap<Integer, Integer> hmFlag = mAdapter.getColor();
		hmFlag.put(mSelectIndex, BG_COLOR);
		hmFlag.put(position, FG_COLOR);
		setColor(hmFlag);
		
		mSelectedView = view;
		mSelectIndex = position;
		
		if (position == 0) {
			
    		mEdit.setEnabled(false);
    		mDelete.setEnabled(false);
    		
		} else {
			
			mEdit.setEnabled(true);
    		mDelete.setEnabled(true);
		}
		
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		
		AlertDialog ad = (AlertDialog) dialog;
		
		if (which == Dialog.BUTTON_POSITIVE) {
			
    		
    		EditText et = (EditText) ad.findViewById(R.id.et_prompt);
    		String pos = et.getText().toString(); // place name
    		
    		if (pos.length() == 0) {
    			
    			Utils.closeAlertDialog(ad, false);
    			
    			Toast.makeText(MgrPositionAct.this, "地名不能为空", Toast.LENGTH_LONG).show();
    			
    			return;
    		}
    		
    		Utils.closeAlertDialog(ad, true);
    		
    //		mGa.getPositions().add(new Position(mStrAddress, pos, mLatLng[0], mLatLng[1]));
    		mGa.getPositions().get(mSelectIndex).setPlace(pos);
    		refreshAdapterData();
    		mAdapter.notifyDataSetChanged();
    		
		} else if (which == Dialog.BUTTON_NEGATIVE) {
			
			Utils.closeAlertDialog(ad, true);
			
			dialog.dismiss();
		}
		
	}

}
